package lt.egidijus.aatest.junit;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.IPackageFragment;
import org.eclipse.jdt.core.IPackageFragmentRoot;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.JavaModelException;


public class JUnitFinder {

	public ArrayList<ICompilationUnit> findJUnitsForProject(IJavaProject project) {
		ArrayList<ICompilationUnit> cus = new ArrayList<ICompilationUnit>();
		try {
			IPackageFragmentRoot[] roots = project.getPackageFragmentRoots();
				for (IPackageFragmentRoot root : roots) {
					if (!root.isArchive()) {
						IJavaElement[] elements = root.getChildren();
						for (IJavaElement element : elements){
							if (element instanceof ICompilationUnit){
								cus.add((ICompilationUnit) element);
							} else if (element instanceof IPackageFragment){
								getAllUnitInPackage(cus, (IPackageFragment) element);
							}
						}
					}
				}

		} catch (JavaModelException e) {

		}
		return cus;
	}
		
	private void getAllUnitInPackage(List<ICompilationUnit> list, IPackageFragment fragment ) throws JavaModelException{
		IJavaElement[] elements = fragment.getChildren();
		for (IJavaElement element : elements){
			if (element instanceof ICompilationUnit){
				list.add((ICompilationUnit) element);
			} else if (element instanceof IPackageFragment){
				getAllUnitInPackage(list, (IPackageFragment) element);
			}
		}
	}
}
